<?php
namespace catchAdmin\wechatopen\controller;

use app\BaseController;
use catcher\CatchResponse;
use catcher\Utils;
use catchAdmin\wechatopen\service\TokenService;
use uctoo\uctoocloud\client\Http;
use catchAdmin\wechatopen\model\WechatopenMiniappUsers;

class MiniappLogin extends BaseController
{
    /**
     * applet 实例
     * @var \catchAdmin\wechatopen\model\Applet
     */
    protected $applet;

    public function initialize()
    {

    }

    public function checktoken()
    {
        $token = input('token');
        $check = (new TokenService())->check($token);
        $res = [
            'check' => $check,
            'msg' => $check ? '校验通过' : '校验失败',
        ];
        return CatchResponse::success($res, '校验token结果');
    }

    //用户小程序端wx.login用code换取token
    public function wxlogin()
    {
        $host = trim(Utils::config('wechatopen.host'));//获取管理后台配置的微信第三方平台地址 http://serv.uctoo.com
        $appid = input('appid');
        $js_code = input('code');
        $account = trim(Utils::config('wechatopen.account'));
        $password = trim(Utils::config('wechatopen.password'));
        $response = Http:: withHost($host)   //指定第三方平台
        ->withVerify(false)    //无需SSL验证
        ->product('/api/wechatopen')    //如果指定产品 则必填参数
        ->post('/sns/component/jscode2session', ['appid' => $appid,'js_code'=>$js_code]);  //当前小程序的appid
        $sessionData = json_decode($response->body(),true);
        $res = (new WechatopenMiniappUsers())->loginByOpenId($appid,$sessionData['data']['openid'],$sessionData['data']);
        return CatchResponse::success( $res,'wxlogin success');
    }

    //用户小程序端wx.getUserProfile授权后，解密用户详细资料
    public function decryptInfo()
    {
        $miniappUser = new WechatopenMiniappUsers;
        $res = $miniappUser->decryptData();
        return CatchResponse::success( $res,'decrypt_info success');
    }

    //用户小程序端授权获取微信绑定手机号码
    public function decryptPhone()
    {
        $miniappUser = new WechatopenMiniappUsers;
        $res = $miniappUser->decryptPhoneData();
        return CatchResponse::success( $res,'decrypt_phone success');
    }

}
